from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from typing import List

from ..models.notebook import Notebook
from ..schemas.notebook import NotebookCreate, NotebookUpdate


class NotebookService:
    """笔记本服务"""
    
    @staticmethod
    def get_notebooks(user_id: int, db: Session) -> List[Notebook]:
        """获取所有笔记本"""
        notebooks = db.query(Notebook)\
                     .filter(Notebook.user_id == user_id)\
                     .all()
        return notebooks
    
    @staticmethod
    def get_notebooks_tree(user_id: int, db: Session) -> List[Notebook]:
        """获取笔记本树形结构"""
        # 获取所有根笔记本（没有父级的）
        root_notebooks = db.query(Notebook)\
                          .filter(
                              Notebook.user_id == user_id,
                              Notebook.parent_id.is_(None)
                          )\
                          .all()
        return root_notebooks
    
    @staticmethod
    def get_notebook(notebook_id: int, user_id: int, db: Session) -> Notebook:
        """获取单个笔记本"""
        notebook = db.query(Notebook).filter(
            Notebook.id == notebook_id,
            Notebook.user_id == user_id
        ).first()
        
        if not notebook:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="笔记本不存在"
            )
        
        return notebook
    
    @staticmethod
    def create_notebook(notebook_data: NotebookCreate, user_id: int, db: Session) -> Notebook:
        """创建笔记本"""
        # 如果有父笔记本，验证父笔记本是否存在
        if notebook_data.parent_id:
            parent = db.query(Notebook).filter(
                Notebook.id == notebook_data.parent_id,
                Notebook.user_id == user_id
            ).first()
            if not parent:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="父笔记本不存在"
                )
        
        notebook = Notebook(
            user_id=user_id,
            name=notebook_data.name,
            parent_id=notebook_data.parent_id
        )
        
        db.add(notebook)
        db.commit()
        db.refresh(notebook)
        return notebook
    
    @staticmethod
    def update_notebook(
        notebook_id: int,
        notebook_data: NotebookUpdate,
        user_id: int,
        db: Session
    ) -> Notebook:
        """更新笔记本"""
        notebook = NotebookService.get_notebook(notebook_id, user_id, db)
        
        update_data = notebook_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(notebook, field, value)
        
        db.commit()
        db.refresh(notebook)
        return notebook
    
    @staticmethod
    def delete_notebook(notebook_id: int, user_id: int, db: Session) -> None:
        """删除笔记本"""
        notebook = NotebookService.get_notebook(notebook_id, user_id, db)
        
        # 检查是否有子笔记本
        if notebook.children:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="该笔记本包含子笔记本，无法删除"
            )
        
        db.delete(notebook)
        db.commit()

